package com.xbongbong.paas.controller;

import com.xbongbong.paas.pojo.dto.AliyunCallSaveAlipayNotifyReqDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.sys.domain.entity.AlipayNotifyEntity;
import com.xbongbong.sys.model.AlipayNotifyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 吴洪波
 * @version v1.0
 * @date 21/06/29 09:48
 * @since v1.0
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/alipay")
public class AliyunCalcenterAlipayController {

    private static final Logger log =  LoggerFactory.getLogger(AliyunCalcenterAlipayController.class);

    @Resource
    private AlipayNotifyModel alipayNotifyModel;

    @RequestMapping(value = "/saveAlipayNotify", method = RequestMethod.POST)
    public XbbResponse<Integer> saveAlipayNotify(@RequestBody @Valid AliyunCallSaveAlipayNotifyReqDTO reqDTO, BindingResult br) {
        XbbResponse<Integer> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                log.info("更新支付宝支付信息 -> {}", reqDTO.toString());
                Integer save = alipayNotifyModel.save(saveNotifyEntity(reqDTO));
                response = new XbbResponse<>(save);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return response;
    }


    public AlipayNotifyEntity saveNotifyEntity(AliyunCallSaveAlipayNotifyReqDTO reqDTO) throws XbbException {
        AlipayNotifyEntity alipayNotifyEntity = new AlipayNotifyEntity();
        BeanUtils.copyProperties(reqDTO, alipayNotifyEntity);
        return alipayNotifyEntity;
    }
}
